package com.qrxl.common.vo;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qrxl.common.exception.CustomException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@ApiModel(value = "分页返回对象", description = "请求参数类")
@Data
public class PageVo<T> {

    @ApiModelProperty(value = "记录列表")
    protected List<T> records = new ArrayList<>();
    @ApiModelProperty(value = "总记录数")
    protected long total=0;
    @ApiModelProperty(value = "当前页")
    protected long current;


    public PageVo(Class<T> clazz, Page page) {
        if (clazz != null) {
            page.getRecords().forEach(bo -> {
                try {
                    T vo = clazz.newInstance();
                    BeanUtils.copyProperties(bo, vo);
                    this.records.add(vo);
                } catch (Exception e) {
                    throw new CustomException("分页对象实例化错误");
                }
            });
        } else {
            // 原样输出（查询数据是vo的情况不需要转换）
            this.records = page.getRecords();
        }

        this.total = page.getTotal();
        this.current = page.getCurrent();
    }

    public PageVo() {
    }
}
